//
//  AVPlayerViewController.m
//  斗鸡TV
//
//  Created by admin on 16/3/11.
//  Copyright © 2016年 admin. All rights reserved.
//

//#define PLAYUrl @"http://asp.cntv.lxdns.com/asp/hls/main/0303000a/3/default/3b0f4309f7a04130a86b00768d0c9786/main.m3u8?maxbr=1200"
#define PLAYUrl @"http://asp.cntv.lxdns.com/asp/hls/850/0303000a/3/default/48968533e8634f9cac463d089d4e740e/850.m3u8"

#define MoreData @"http://suggest.cntvwb.cn/cntv-rec/recommend/0/1/1/C1809948-1C96-4397-944F-E94EE8FBF6B9/cee94fd627984af590eed6a543f94698"

#import "AVPlayerViewController.h"
#import "MoreNewsViewCell.h"
#import "ApplicitonClass.h"
#import <MediaPlayer/MPMusicPlayerController.h>

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
#define VolumeStep 0.02f
#define BrightnessStep 0.02f
#define MovieProgressStep 5.0f

@class MPMusicPlayerApplicationController;

typedef NS_ENUM(NSInteger, GestureType){
    GestureTypeOfNone = 0,
    GestureTypeOfVolume,
    GestureTypeOfBrightness,
    GestureTypeOfProgress,
};

@interface AVPlayerViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,LoadHttpDataDelegate>
{
    BOOL isChange;
    AVPlayerItem *playerItem;
   
    UIButton * bigBtn;
    UIView * superView;
    CGFloat totalSecond;
    NSMutableArray * allArray;
    UITableView * tbView;
    NSString * playID;
    BOOL isPlay;
    BOOL isStarPlay;
    UIButton * pauseBtn;
    SubWaQuModel * sHM;
    CGFloat currentSecond;
    UIButton * backBtn;
    
    
   
}
@property (strong,nonatomic) AVPlayer *player;
@property (strong,nonatomic)AVPlayerLayer *playerLayer;
@property (strong,nonatomic) NSString * timeStr;
@property (strong,nonatomic) UILabel * timeLable;
@property (strong,nonatomic)  UIProgressView * videoProgress;
@property (strong,nonatomic)  UIProgressView * playProgress;
@property (strong,nonatomic)   UISlider * slider;
@property (nonatomic,strong)UIImageView *brightnessView;
@property (nonatomic,strong)UIProgressView *brightnessProgress;

@property (nonatomic,assign)GestureType gestureType;
@property (nonatomic,assign)CGPoint originalLocation;
@property (nonatomic,assign)CGFloat progressValue;
@property (nonatomic,assign)__block CGFloat currentSecond;
@end

@implementation AVPlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//     [self setWebView];
    isPlay = YES;
    allArray = [NSMutableArray new];
    
    [self setAVPlay];
    [self loadMore];
    
    CGFloat tbViewY = CGRectGetMaxY(superView.frame);
    tbView = [[UITableView alloc]initWithFrame:CGRectMake(0, tbViewY, WIDTH, HEIGHT-tbViewY) style:UITableViewStylePlain];
    tbView.delegate = self;
    tbView.dataSource = self;
    tbView.rowHeight = 70;
    [self.view addSubview:tbView];
    

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished)name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stopPlay) name:@"stopPlay" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(play) name:@"Play" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeRotate:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    
    [ApplicitonClass getInstance].isflag = YES;
    
    
    
    
    
    NSArray*audioTracks = [playerItem.asset tracksWithMediaType:AVMediaTypeVideo];
    NSMutableArray*allAudioParams = [NSMutableArray array];
    
    for (AVAssetTrack *track in audioTracks) {
        
        AVMutableAudioMixInputParameters*audioInputParams = [AVMutableAudioMixInputParameters audioMixInputParameters];
        [audioInputParams setVolume:1.0 atTime:kCMTimeZero];
        [audioInputParams setTrackID:[track trackID]];
        [allAudioParams addObject:audioInputParams];
    }
    
    
    AVMutableAudioMix*audioMix = [AVMutableAudioMix audioMix];
    [audioMix setInputParameters:allAudioParams];
    [playerItem setAudioMix:audioMix];
}

- (BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    
    return YES;
}

//-(void)panMove:(UIPanGestureRecognizer *)pan
//{
//    
//    if (isStarPlay) {
//        
//        CGPoint translation = [pan translationInView:superView];
//        NSLog(@"%f",translation.x);
//        
//        //    [pan setTranslation:CGPointZero inView:superView];
//        
//        CGFloat currentSecond = playerItem.currentTime.value / playerItem.currentTime.timescale;// 计算当前在第几秒
//        
//        NSLog(@"====%f",currentSecond);
//        NSLog(@"++++%f",currentSecond + translation.x);
//        double currentTime;
//        currentTime = floor(currentSecond + translation.x);
//        NSLog(@"-----%g",currentTime);
//        
//        self.slider.value = currentTime / totalSecond;
//        
//        //转换成CMTime才能给player来控制播放进度
//        CMTime dragedCMTime = CMTimeMake(currentTime, 1);
//        [player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
//            
//            [player play];
//            
//        }];
//    }
//
//}


-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if(!superView.isUserInteractionEnabled){
        return;
    }
    UITouch *touch = [touches anyObject];
    CGPoint currentLocation = [touch locationInView:superView];
    CGFloat offset_x = currentLocation.x - _originalLocation.x;
    CGFloat offset_y = currentLocation.y - _originalLocation.y;
//     NSLog(@"%f----%f",currentLocation.x,_originalLocation.x);
    if (CGPointEqualToPoint(_originalLocation,CGPointZero)) {
        _originalLocation = currentLocation;
        return;
    }
    _originalLocation = currentLocation;
    
    if (_gestureType == GestureTypeOfNone) {
        if ((currentLocation.x > WIDTH*0.8) && (ABS(offset_x) <= ABS(offset_y))) {
            
            _gestureType = GestureTypeOfVolume;
            NSLog(@"呻吟");
            
        }else if ((currentLocation.x < WIDTH*0.2) && (ABS(offset_x) <= ABS(offset_y))) {
            
            _gestureType = GestureTypeOfBrightness;
            NSLog(@"亮度");
            
        }else if ((ABS(offset_x) > ABS(offset_y))) {
            
            _gestureType = GestureTypeOfProgress;
            NSLog(@"进度");
            
        }
    }
    if ((_gestureType == GestureTypeOfProgress) && (ABS(offset_x) > ABS(offset_y))) {
        if (offset_x > 0) {
            NSLog(@"横向向右%f",offset_x);
            self.currentSecond += 1;
        }else{
            NSLog(@"横向向左%f",offset_x);
            self.currentSecond -= 1;
        }
        
        NSString * currentTime = [self convertTime:self.currentSecond];
        self.timeLable.text = [NSString stringWithFormat:@"%@/%@",currentTime,self.timeStr];
        self.slider.value = self.currentSecond/totalSecond;
        
    }else if ((_gestureType == GestureTypeOfVolume) && (currentLocation.x > WIDTH*0.8) && (ABS(offset_x) <= ABS(offset_y))){
        if (offset_y > 0){
            NSLog(@"右竖向向下");
            [self volumeAdd:-VolumeStep];
        }else{
            NSLog(@"右竖向向上");
            [self volumeAdd:VolumeStep];
        }
    }else if ((_gestureType == GestureTypeOfBrightness) && (currentLocation.x < WIDTH*0.2) && (ABS(offset_x) <= ABS(offset_y))){
        if (offset_y > 0) {
            NSLog(@"左竖向向下");
            _brightnessView.alpha = 1;
            
            [self brightnessAdd:-BrightnessStep];
        }else{
            NSLog(@"左竖向向下");
            
            _brightnessView.alpha = 1;
            [self brightnessAdd:BrightnessStep];
        }
    }
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

    //设置滑动类型
    if (_gestureType == GestureTypeOfNone ) {
        
    }else if (_gestureType == GestureTypeOfProgress){
        _gestureType = GestureTypeOfNone;
        double currentTime = floor(self.currentSecond);
        //转换成CMTime才能给player来控制播放进度
        CMTime dragedCMTime = CMTimeMake(currentTime, 1);
        [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
            
            [self.player play];
            
        }];
        if (_brightnessView.alpha) {
            [UIView animateWithDuration:1 animations:^{
                _brightnessView.alpha = 0;
            }];
        }

        _progressValue = 0;
    }
    else {
        _progressValue = 0;
        _gestureType = GestureTypeOfNone;
        if (_brightnessView.alpha) {
            [UIView animateWithDuration:1 animations:^{
                _brightnessView.alpha = 0;
            }];
        }
    }

}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    _originalLocation = CGPointZero;
    NSLog(@"起点：%f",CGPointZero.x);
    
}

- (void)brightnessAdd:(CGFloat)step{
    [UIScreen mainScreen].brightness += step;
    _brightnessProgress.progress = [UIScreen mainScreen].brightness;
    
}
- (void)volumeAdd:(CGFloat)step{
    [MPMusicPlayerController applicationMusicPlayer].volume += step;
}



//暂停／播放
-(void)pauseClick
{
    isPlay = !isPlay;
    if (isPlay) {
        
        //暂停播放
        [self.player pause];
        
        [pauseBtn setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        
    }else{
        
        //播放
        [self.player play];
        
        [pauseBtn setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
    }

}

-(void)play
{
    //播放
    [self.player play];
    
}
-(void)stopPlay
{
    //暂停播放
    [self.player pause];
}

-(void)loadMore
{
   
    NSString * str;
    if (self.mid) {
        
        str = [NSString stringWithFormat:@"http://www.waqu.com/v4/qudan/videoCards.json?appName=general_video&appVersion=3.6.6&fTitle=true&isMakeQudan=0&partner=0100&platform=ios&posByHistory=false&profile=general_men&qdid=%@&sid=cd18452f65ece0686810e3b45c97857f&size=100&start=0",self.mid];
    }else{
         str = [NSString stringWithFormat:@"http://suggest.cntvwb.cn/cntv-rec/recommend/0/1/1/C1809948-1C96-4397-944F-E94EE8FBF6B9/%@",_sm.vid];
    }
   
    
    //使用代理封装AFN
    ApplicitonClass * appLiciton = [ApplicitonClass getInstance];
    if (self.mid)
    {
        [appLiciton httpGetUrl:str params:nil];
    }else
    {
        [appLiciton httpPOSTUrl:str params:nil];
    }
    
    appLiciton.delegate = self;
    
//    [self httpPostUrl:str params:nil successBlock:^(NSDictionary *dict) {
//          NSLog(@"%@",dict);
//        if (dict) {
//            
//            NSArray * array = [dict arrayForKey:@"hotRes"];
//            NSArray * arrays = [dict arrayForKey:@"newRes"];
//            [allArray addObjectsFromArray:array];
//            [allArray addObjectsFromArray:arrays];
//            NSLog(@"%@",allArray);
//        }
//      
//        [tbView reloadData];
//    } errorBlock:^(NSError *error) {
//        
//        
//    }];
   
}

//网络请求成功delegate
-(void)successWithResponse:(id)response
{
    
    if (self.mid || self.wuquModel) {
        
        NSDictionary * dict = response;
        NSLog(@"%@",dict);
        if (dict) {
            
            NSArray * array = [dict arrayForKey:@"cards"];
            if (array)
            {
                for (NSDictionary * dic in array) {
                    
                    NSDictionary * dict = [dic dictionaryForKey:@"video"];
                    
                    sHM = [[SubWaQuModel alloc] initWithDictionary:dict error:nil];
                    if (sHM) {
                        
                        [allArray addObject:sHM];
                    }
                }
                
            }
            
        }
    }else
    {
        NSDictionary * dict = response;
        NSLog(@"%@",dict);
        if (dict) {
            
            NSArray * array = [dict arrayForKey:@"hotRes"];
            NSArray * arrays = [dict arrayForKey:@"newRes"];
            [allArray addObjectsFromArray:array];
            [allArray addObjectsFromArray:arrays];
          
        }
        
        
    }
      NSLog(@"%@",allArray);
    [tbView reloadData];
}

//网络请求失败delegate
-(void)failedWithResponse:(id)request Error:(NSError *)error
{
    NSLog(@"%@",[NSString stringWithFormat:@"%@",error]);
    [self showError:[NSString stringWithFormat:@"%@",error]];
}



-(void)playbackFinished
{
    [self showAlert:@"播放完毕！" CancelBlock:^{
        
       [self popBackViewController];
        
    } OkBlock:^{
        
        
    }];
}

-(void)backTap
{
    [self popBackViewController];
}


-(void)setAVPlay
{
    isStarPlay = NO;
    [superView removeFromSuperview];
    [self removeRevce];
    [self showLoading];

    superView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, WIDTH, 300)];
    superView.backgroundColor = [UIColor blackColor];
    superView.userInteractionEnabled = NO;
    [self.view addSubview:superView];
    
    NSString * strUrl;
    NSString * pid;

    if (self.wuquModel) {
        
        if (playID) {
            
            pid = playID;
        }else{
            pid = self.wuquModel.wid;
        }
        
        strUrl = @"http://vssauth.waqu.com/8961f96mx473v90q/hd2_mts.mp4?auth_key=1499352827-0-0-7f014cd028def70540b8666fd8561a65";
        //[NSString stringWithFormat:@"http://les.waqu.com/%@/normal.mp4",pid];
        
    }else if (self.sHM)
    {
        if (playID) {
            
        strUrl = [NSString stringWithFormat:@"http://asp.cntv.lxdns.com/asp/hls/main/0303000a/3/default/%@/main.m3u8?maxbr=1200",playID];
        }else{
              strUrl = self.sHM.flv; 
        }
        
       
    }else
    {
        if (playID) {
            
            pid = playID;
        }else{
            pid = _sm.vid;
        }
        
        strUrl = [NSString stringWithFormat:@"http://asp.cntv.lxdns.com/asp/hls/main/0303000a/3/default/%@/main.m3u8?maxbr=1200",pid];
    }
    NSURL *videoUrl = [NSURL URLWithString:strUrl];
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:videoUrl options:nil];
    

    playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    // 监听status / loadedTimeRanges属性
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    _playerLayer.frame = superView.bounds;
    [superView.layer addSublayer:_playerLayer];
    [self.player play];
    
    
    //缓冲进度条
    self.videoProgress = [[UIProgressView alloc]initWithFrame:CGRectMake(20, superView.frame.size.height-35, superView.frame.size.width-40 , 20)];
    self.videoProgress.trackTintColor = [UIColor whiteColor];
    self.videoProgress.progressTintColor = [UIColor lightGrayColor];
    [superView addSubview: self.videoProgress];
    
    //播放进度条
    CGFloat sliderY = CGRectGetMinY(self.videoProgress.frame);
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(20, sliderY-9, superView.frame.size.width-40 , 20)];
    self.slider.maximumTrackTintColor = [UIColor clearColor];
    [self.slider addTarget:self action:@selector(changValue:) forControlEvents:UIControlEventValueChanged];
    [self.slider addTarget:self action:@selector(touchDown:) forControlEvents:UIControlEventTouchDown];
    [self.slider addTarget:self action:@selector(touchUp:) forControlEvents:UIControlEventTouchUpInside];
    [superView addSubview: self.slider];
    
    //横屏按钮
    bigBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-30, superView.frame.size.height-30, 30, 30)];
//    bigBtn.backgroundColor = [[UIColor orangeColor]colorWithAlphaComponent:0.5];
    [bigBtn setImage:[UIImage imageNamed:@"all"] forState:UIControlStateNormal];
    [bigBtn addTarget:self action:@selector(changeView) forControlEvents:UIControlEventTouchUpInside];
    [superView addSubview:bigBtn];
    
    _timeLable = [[UILabel alloc]initWithFrame:CGRectMake(40,superView.frame.size.height-30, 150, 30)];
    _timeLable.textColor = [UIColor whiteColor];
//        _timeLable.backgroundColor = [UIColor orangeColor];
    [superView addSubview:_timeLable];
    //返回按钮
    backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 30, 30, 30)];
    [backBtn setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    backBtn.layer.borderWidth = 2;
    backBtn.layer.cornerRadius = 15;
    backBtn.layer.borderColor = [[UIColor whiteColor]CGColor];
    [backBtn addTarget:self action:@selector(backTap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview: backBtn];
    
    pauseBtn = [[UIButton alloc]initWithFrame:CGRectMake(5, superView.frame.size.height-30, 30, 30)];
    
    [pauseBtn setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
    [pauseBtn addTarget:self action:@selector(pauseClick) forControlEvents:UIControlEventTouchUpInside];
    [superView addSubview:pauseBtn];
    
    //亮度调节图标
    _brightnessView = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width/2, self.view.frame.size.height/2, 125, 125)];
    _brightnessView.image = [UIImage imageNamed:@"video_brightness_bg.png"];
    _brightnessProgress = [[UIProgressView alloc]initWithFrame:CGRectMake(_brightnessView.frame.size.width/2, _brightnessView.frame.size.height/2-30, 80, 10)];
    _brightnessProgress.trackImage = [UIImage imageNamed:@"video_num_bg.png"];
    _brightnessProgress.progressImage = [UIImage imageNamed:@"video_num_front.png"];
    _brightnessProgress.progress = [UIScreen mainScreen].brightness;
    [_brightnessView addSubview:_brightnessProgress];
    [superView addSubview:_brightnessView];
    _brightnessView.alpha = 0;
    _brightnessView.frame = CGRectMake(WIDTH/2-63, superView.frame.size.height/2, 125, 125);
    _brightnessProgress.frame = CGRectMake(25, 100, 80, 10);
    

}

-(void)touchUp:(UISlider *)slider
{
    NSLog(@"抬起");
    [self play];
}
-(void)touchDown:(UISlider *)slider
{
    [self stopPlay];
    NSLog(@"按下");
}
//控制视频的播放进度
-(void)changValue:(UISlider *)slider
{
    
    NSLog(@"%f",slider.value);
    
    double currentTime = floor(totalSecond * slider.value);
    //转换成CMTime才能给player来控制播放进度
    CMTime dragedCMTime = CMTimeMake(currentTime, 1);
    [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
    
        [self.player play];
        
    }];
}


#pragma mark - tableView  数据源代理


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return allArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * ID = @"cell";
    MoreNewsViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        
        cell = [[MoreNewsViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    NSDictionary * dic = allArray[indexPath.row];
     if (self.mid || self.wuquModel)
     {
          SubWaQuModel * wuquM = allArray[indexPath.row];
         [cell setCellData:wuquM];
     }else
     {
         [cell initCellData:dic];
     }
    
    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     if (self.mid || self.wuquModel)
     {
         SubWaQuModel * wuquM = allArray[indexPath.row];
         playID = wuquM.wid;
     }else
     {
         NSDictionary * dic = allArray[indexPath.row];
         playID = [dic stringForKey:@"contGuid"];
         
     }

    [self setAVPlay];
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel * headLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 20)];
    headLable.text = @"相关视频";
    headLable.textAlignment = NSTextAlignmentCenter;
    headLable.backgroundColor = [UIColor lightGrayColor];
    return headLable;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

//横屏
-(void)changeView
{
    [UIView animateWithDuration:0.3 animations:^{
        if (!isChange) {
            
            [self rightRotation];
            isChange = YES;
        }else
        {
            [self leftRotation];
            isChange = NO;
        }
        
        
        
    }];
    
}

 //横屏
-(void)rightRotation
{
    tbView.hidden = YES;
    superView.transform = CGAffineTransformMakeRotation(M_PI_2);
    _timeLable.frame = CGRectMake(64,WIDTH-30, 150, 30);
    superView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    _playerLayer.frame = superView.bounds;
    bigBtn.frame = CGRectMake(HEIGHT-30,WIDTH-30, 30, 30);
    self.videoProgress.frame = CGRectMake(20,WIDTH-35, superView.frame.size.height-40, 20);
    CGFloat sliderY = CGRectGetMinY(self.videoProgress.frame);
    self.slider.frame = CGRectMake(20, sliderY-9, superView.frame.size.width-40 , 20);
    self.playProgress.frame = self.videoProgress.frame;
    pauseBtn.frame = CGRectMake(20,WIDTH-30, 30, 30);
    [bigBtn setImage:[UIImage imageNamed:@"exit.jpg"] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(WIDTH-30, 40, 30 , 30);
}

 //竖屏
-(void)leftRotation
{
    tbView.hidden = NO;
    superView.transform = CGAffineTransformRotate(superView.transform, -M_PI_2);
    superView.frame = CGRectMake(0, 20, WIDTH, 300);
    _playerLayer.frame = superView.bounds;
    bigBtn.frame = CGRectMake(WIDTH-30, superView.frame.size.height-30, 30, 30);
    _timeLable.frame = CGRectMake(40,superView.frame.size.height-30, 150, 30);
    self.videoProgress.frame = CGRectMake(20, superView.frame.size.height-35, superView.frame.size.width-40 , 20);
    self.playProgress.frame = self.videoProgress.frame;
    CGFloat sliderY = CGRectGetMinY(self.videoProgress.frame);
    self.slider.frame = CGRectMake(20, sliderY-9, superView.frame.size.width-40 , 20);
    pauseBtn.frame = CGRectMake(5, superView.frame.size.height-30, 30, 30);
    [bigBtn setImage:[UIImage imageNamed:@"all"] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(10, 30, 30 , 30);
}

- (void)changeRotate:(NSNotification*)noti {
    if ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortrait
        || [[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortraitUpsideDown) {
    
        NSLog(@"竖屏");
        tbView.hidden = NO;
        superView.frame = CGRectMake(0, 20, WIDTH, 300);
        _playerLayer.frame = superView.bounds;
        bigBtn.frame = CGRectMake(WIDTH-30, superView.frame.size.height-30, 30, 30);
        _timeLable.frame = CGRectMake(40,superView.frame.size.height-30, 150, 30);
        self.videoProgress.frame = CGRectMake(20, superView.frame.size.height-35, superView.frame.size.width-40 , 20);
        self.playProgress.frame = self.videoProgress.frame;
        CGFloat sliderY = CGRectGetMinY(self.videoProgress.frame);
        self.slider.frame = CGRectMake(20, sliderY-9, superView.frame.size.width-40 , 20);
        pauseBtn.frame = CGRectMake(5, superView.frame.size.height-30, 30, 30);
        [bigBtn setImage:[UIImage imageNamed:@"all"] forState:UIControlStateNormal];
        [ApplicitonClass getInstance].isflag = YES;
    } else {
        NSLog(@"横屏");
        
        tbView.hidden = YES;
        _timeLable.frame = CGRectMake(64,WIDTH-30, 150, 30);
        superView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
        _playerLayer.frame = superView.bounds;
        bigBtn.frame = CGRectMake(HEIGHT-30,WIDTH-30, 30, 30);
        self.videoProgress.frame = CGRectMake(20,WIDTH-35, superView.frame.size.height-40, 20);
        CGFloat sliderY = CGRectGetMinY(self.videoProgress.frame);
        self.slider.frame = CGRectMake(20, sliderY-9, superView.frame.size.width-40 , 20);
        self.playProgress.frame = self.videoProgress.frame;
        pauseBtn.frame = CGRectMake(20,WIDTH-30, 30, 30);
        [bigBtn setImage:[UIImage imageNamed:@"exit.jpg"] forState:UIControlStateNormal];
        
        [ApplicitonClass getInstance].isflag = NO;
    }
}


//KVO 监听播放状态
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
//    NSLog(@"%@",keyPath);
    __weak AVPlayerViewController * weakslef = self;
    AVPlayerItem * playItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"])
    {
        
        if ([playItem status] == AVPlayerItemStatusReadyToPlay)
        {
            isStarPlay = YES;
//            CMTime duration = playerItem.duration; //获取视频长度
             totalSecond = playerItem.duration.value / playerItem.duration.timescale;//转换成秒
            _timeStr = [weakslef convertTime:totalSecond];
            [weakslef monitoringPlayback:playerItem];// 监听播放状态
            NSLog(@"++++++time%@",_timeStr);
            [self dismissLoading];
        }else if ([playerItem status] == AVPlayerStatusUnknown)
        {
            NSLog(@"正在加载");
        }
        else if ([playerItem status] == AVPlayerStatusFailed) {
            NSLog(@"======AVPlayerStatusFailed");
            [self dismissLoading];
            [weakslef PlayStast];
            
        }

        superView.userInteractionEnabled = YES;
    }else if ([keyPath isEqualToString:@"loadedTimeRanges"])
    {
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
        CMTime duration = playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        [self.videoProgress setProgress:timeInterval / totalDuration animated:YES];
        
       
    }

}



- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}

//播放失败提醒
-(void)PlayStast
{
    
    [self showError:@"播放失败"];
//    [self showAlert:@"播放失败，是否重新加载？" CancelBlock:^{
//        
//         [self popBackViewController];
//        
//    } OkBlock:^{
//        
//        [self setAVPlay];
//        
//    }];
    

}

//用于监听每秒的状态
- (void)monitoringPlayback:(AVPlayerItem *)playerIte {
    

    __weak AVPlayerViewController * weakslef = self;
     [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        weakslef.currentSecond = playerItem.currentTime.value / playerItem.currentTime.timescale;// 计算当前在第几秒

        NSString * currentTime = [weakslef convertTime:weakslef.currentSecond];
        weakslef.timeLable.text = [NSString stringWithFormat:@"%@/%@",currentTime,weakslef.timeStr];
         
         
         weakslef.slider.value = weakslef.currentSecond/totalSecond;
         
    }];
}


- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (second/3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    } else {
        [formatter setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [formatter stringFromDate:d];
    return showtimeNew;
}

//设置导航栏图片
-(void)setnavigationTouMing:(NSString *)img
{
    UIImage *image = [UIImage imageNamed:img];
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:image];
}


//-(void)setWebView
//{
//    UIWebView * webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
//     [webView setUserInteractionEnabled:YES];
//    [webView setScalesPageToFit:YES];//自动缩放以适应屏幕
//    [self.view addSubview:webView];
//    
//    NSString * webRul = [NSString stringWithFormat:@"http://tv.cntv.cn/videoset/%@",_sm.vsetId];
//    NSURL *url = [NSURL URLWithString:webRul];
//    [webView loadRequest:[NSURLRequest requestWithURL:url]];
//}


// 移除监听
-(void)viewWillDisappear:(BOOL)animated
{
    [self removeRevce];
    self.navigationController.navigationBarHidden = NO;
     [self dismissLoading];
     [ApplicitonClass getInstance].isflag = NO;
}

-(void)removeRevce
{
    [self.player replaceCurrentItemWithPlayerItem:nil];
    [playerItem cancelPendingSeeks];
    [playerItem.asset cancelLoading];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    [playerItem removeObserver:self forKeyPath:@"status" context:nil];
}


-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden=YES;
    self.navigationController.navigationBarHidden = YES;
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
